<template>
  <p-select
    v-if="isEdit"
    class="default-select-container"
    :value="value"
    :placeholder="placeholder"
    :disabled="disabled"
    :allow-clear="allowClear"
    :show-arrow="!disabled"
    @change="handleChange"
  >
    <!-- 不要修改下面格式，有bug label 会加上空格 -->
    <!-- eslint-disable vue/singleline-html-element-content-newline -->
    <!-- prettier-ignore -->
    <p-select-option
      v-for="item in mergeOptions"
      :key="item.value"
      :value="item.value"
    >{{ item.label }}</p-select-option>
  </p-select>
  <span v-else class="ellipsis" :style="{ width: width }">
    {{ selectType[value] }}
  </span>
</template>

<script>
import { getDicList } from '@/api/public.js';

const all = { label: '全部', value: '' };
export default {
  props: {
    allowClear: {
      type: Boolean,
      default: true,
    },
    labelInValue: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [Number, String],
      default: '',
    },
    hasDefault: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: '80px',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    hasAll: {
      type: Boolean,
      default: true,
    },
    options: {
      type: Array,
      default: () => [],
    },
    code: {
      type: String,
      default: 'plan_node',
    },
    isEdit: {
      type: Boolean,
      default: true,
    },
    selectType: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      codeOptions: [],
    };
  },
  computed: {
    mergeOptions() {
      return this.options.length ? this.options : this.codeOptions;
    },
  },
  watch: {
    code: {
      handler() {
        this.getDicList();
      },
      immediate: true,
    },
  },
  methods: {
    async getDicList() {
      if (this.options.length) {
        if (!this.value && this.hasDefault) {
          this.$emit('input', this.options[0]?.value);
        }
        return;
      }
      const result = await getDicList(this.code);
      const data = result?.data?.data || [];
      if (this.hasAll) {
        if (!data.length) return [];
        this.codeOptions = [all, ...data];
      } else {
        this.codeOptions = data;
        if (!this.value && this.hasDefault) {
          this.$emit('input', data[0]?.value);
        }
      }
    },
    handleChange(value) {
      this.$emit('input', value);
    },
  },
};
</script>

<style lang="less" scoped>
.default-select-container {
  width: 100%;
}
.poros-select-disabled {
  color: #040c2c;
  /deep/ .poros-select-selection {
    background: transparent !important;
    cursor: default !important;
    border: none;
  }
}
</style>
